package com.fenghongzhang.broadcasttest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Main3Activity extends AppCompatActivity {
    private TextView name;
    private Button sendBC;

    private MyReceiver myReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        name = (TextView) findViewById(R.id.name);
        sendBC = (Button) findViewById(R.id.sendBC);

        //动态注册
         myReceiver =new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.feng");
        registerReceiver(myReceiver,intentFilter);

        sendBC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置频道
                Intent intent = new Intent();
                intent.setAction("com.feng");

                //加数据
                Bundle bundle = new Bundle();
                bundle.putString("name","程小姐");
                intent.putExtras(bundle);

                sendBroadcast(intent);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

    public class MyReceiver extends BroadcastReceiver {

        public MyReceiver(){
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals("com.feng")){
                Bundle extras = intent.getExtras();
                String name1 = extras.getString("name");
                name.setText(name1);
            }
        }
    }
}
